package com.hitqz.robot.biz.flow.component.agv;

import cn.hutool.json.JSONObject;
import com.hitqz.robot.api.business.model.dto.FlowContextDto;
import com.hitqz.robot.api.business.model.dto.FlowPatrolPreAndEndTicketsDto;
import com.hitqz.robot.biz.flow.domain.constant.FlowConstant;
import com.hitqz.robot.biz.flow.util.LiteFlowUtil;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author xupkun
 * @date 2025/3/30
 */
@Slf4j
@LiteflowComponent(value = "getEquipmentStatus", name = "[轮对/轮轴]AGV获取设备状态")
@RequiredArgsConstructor
public class GetEquipmentStatus extends NodeComponent {


    private final RestTemplate restTemplate;

    @Override
    public void process() throws Exception {
        LiteFlowUtil.checkInterruptFlag();
        FlowContextDto dto =  this.getRequestData();
        FlowPatrolPreAndEndTicketsDto ticketsDto = com.alibaba.fastjson.JSONObject.parseObject(dto.getTicketsTask()
                .getParseOrderParams(), FlowPatrolPreAndEndTicketsDto.class);
        String uri = this.getCmpData(JSONObject.class).get(FlowConstant.NODE_CUSTOM_INFO_MAP.get(this.getNodeId()).getParamNames().get(0), String.class).trim();
        String checkResult = this.getCmpData(JSONObject.class).get(FlowConstant.NODE_CUSTOM_INFO_MAP.get(this.getNodeId()).getParamNames().get(1), String.class);
        String targetName = Optional.ofNullable(ticketsDto.getModalData().get("targetPosName"))
                .orElse(ticketsDto.getModalData().get("targetPosCode")).toString();
        while (true) {
            LiteFlowUtil.checkInterruptFlag();
            String result = restTemplate.getForObject(
                    uri, String.class);
            log.info("{} 请求设备状态: {}", uri, result);
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);
            if (jsonObject.containsKey("data") && checkResult.equals(jsonObject.getString("data"))) {
                log.info(" {} 可以上料: 期待值{}-- 目标值{}", targetName, checkResult, jsonObject.getString("data"));
                break;
            }
            TimeUnit.SECONDS.sleep(5);
        }
    }
}
